package com.nidu.demo.notify.executor.command;

import com.alibaba.cola.dto.Response;
import com.alibaba.cola.exception.BizException;
import com.nidu.demo.common.constants.Constants;
import com.nidu.demo.common.exception.ErrorCodeConstants;
import com.nidu.demo.notify.gateway.NotifyMessageGateway;
import com.nidu.demo.notify.model.NotifyMessage;
import com.nidu.demo.notify.model.NotifyMessageCriteria;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Set;

/**
 * 站内信更新命令执行器
 *
 * @author auto
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class NotifyMessageUpdateCmdExe {

    private final NotifyMessageGateway gateway;

    public Response updateReadStatus(Long id) {
        // 1. 检查消息是否存在
        NotifyMessage message = gateway.getById(id);
        if (message == null) {
            throw new BizException(ErrorCodeConstants.NOTIFY_MESSAGE_NOT_FOUND.getCode(), ErrorCodeConstants.NOTIFY_MESSAGE_NOT_FOUND.getMessage());
        }

        // 2. 是否标记已读
        message.isRead();

        // 3. 标记为已读
        gateway.updateReadStatus(id);

        return Response.buildSuccess();
    }

    @Transactional
    public Response updateReadStatus(Set<Long> ids) {
        // 1. 查询用户所有未读消息
        NotifyMessageCriteria criteria = new NotifyMessageCriteria();
        criteria.setIds(ids);
        List<NotifyMessage> messages = gateway.listByCondition(criteria);

        // 2. 批量标记为已读
        messages.forEach(message -> {
            message.isRead();
            this.updateReadStatus(message.getId());
        });

        return Response.buildSuccess();
    }
}
